package com.geralt.im.gui;

import geralt.im.watcher.Observer;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import com.geralt.im.entrance.Entrance;
import com.geralt.im.model.Message;
import com.geralt.im.protocol.Request;

public class ClientGUI extends JFrame implements Observer {

	private JTextField editArea = null;
	private JTextArea disArea = null;
	private JButton send = null;
	private JButton pow = null;
	private JLabel displayLabel = new JLabel("user list                  ");
	private JLabel informationLabel = null;

	private DefaultListModel usersModel = null;
	private JList nameList = null;
	private Vector selectedElement = null;

	private JPanel displayPanel = new JPanel();
	private JPanel textPanel = new JPanel();
	private JPanel listPanel = new JPanel();
	private JPanel labelPanel = new JPanel();

	private JPanel editTextPanel = new JPanel();

	private JTabbedPane jTab = new JTabbedPane();
	private String[] tabNames = { "chat", "" };
	ImageIcon icon = createImageIcon("image/middel.jpg");
	private JScrollPane jScrollpane = new JScrollPane();
	public ClientGUI() {
		setSize(600, 700);
		setLocation(300, 100);
		setTitle("bb chat room vol.1");
		setResizable(false);

		setLayout(new BorderLayout());

		displayPanelCreate();
		textPanelCreate();
		listPanelCreate();
		labelPanelCreate();
		editTextPanelCreate();

		int i = 0;
		jTab.addTab(tabNames[i++], icon, displayPanel, "first");

		add(labelPanel, BorderLayout.NORTH);
		add(textPanel, BorderLayout.CENTER);
		add(listPanel, BorderLayout.EAST);
		pack();
		addListener();
	}

	private ImageIcon createImageIcon(String string) {
		return new ImageIcon("dd");
	}

	private void displayPanelCreate() {
		disArea = new JTextArea(20, 40);
		JScrollPane pane = new JScrollPane(disArea);
		displayPanel.add(pane);
	}

	private void editTextPanelCreate() {
		editArea = new JTextField(30);
		JScrollPane pane = new JScrollPane(editArea);
		send = new JButton("send");
		pow = new JButton("pow");
		editTextPanel.add(pane);
		editTextPanel.add(send);
		editTextPanel.add(pow);
	}

	private void textPanelCreate() {
		textPanel.setSize(22, 35);
		textPanel.setLayout(new BorderLayout());

		textPanel.add(jTab, BorderLayout.NORTH);
		textPanel.add(editTextPanel, BorderLayout.SOUTH);
	}

	private void listPanelCreate() {
		listPanel.setLayout(new BorderLayout());
		usersModel = new DefaultListModel();
		nameList = new JList(usersModel);
		nameList.setFixedCellWidth(100);
		selectedElement = new Vector();
		jScrollpane = new JScrollPane(nameList);
		listPanel.add(nameList, BorderLayout.CENTER);
		listPanel.add(displayLabel, BorderLayout.NORTH);
	}

	private void labelPanelCreate() {
		labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		informationLabel = new JLabel("chatting");
		labelPanel.add(informationLabel);
	}

	public void addListener() {
		send.addActionListener(sendBtnListener);
		nameList.addMouseListener(nameListClickedListener);
		addWindowListener(onClientClosingAdapter);
		pow.addActionListener(powBtnListener);
	}

	ActionListener sendBtnListener = new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			String getText = editArea.getText();
			if("".equals(getText)){
				JOptionPane.showMessageDialog(null,"you can't send empty message", "Error",
						JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			String id = (String) nameList.getSelectedValue();
			if (id == null) {
				id = "ALL";
			}
			if (id.compareTo(Entrance.customer.getId()) != 0) {
				Request request = new Request();
				request.setType("SEND");
				Message msg = new Message();
				msg.setContent(getText);
				msg.setFrom(Entrance.customer.getId());
				msg.setTo(id);
				request.getParameter().put("SEND", msg);
				// System.out.println(id); ///////////
				Entrance.client.getClientRunner().write(request);
				editArea.setText("");
			}
		}
	};

	MouseListener nameListClickedListener = new MouseAdapter() {
		public void mouseClicked(MouseEvent mouseEvent) {
			JList theList = (JList) mouseEvent.getSource();
			// if (mouseEvent.getClickCount() == 2) {
			String name = (String) theList.getSelectedValue();
			Entrance.reciever = name;
			informationLabel.setText("you are talking with:" + name);
			// }
		}
	};

	WindowAdapter onClientClosingAdapter = new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
			if (Entrance.client.flag != false) {
				Entrance.client.flag = false;
//				Request request = new Request();
//				request.setType("EXIT");
//				request.getParameter().put("EXIT", Entrance.customer.getId());
//				System.out.println(request.toString());
//				Entrance.client.getClientRunner().write(request);
				setDefaultCloseOperation(EXIT_ON_CLOSE);
			}
		}
	};

	ActionListener powBtnListener = new ActionListener() {

		public void actionPerformed(ActionEvent e) {
			String id = (String) nameList.getSelectedValue();
			if (id == null) {
				id = "ALL";
			}
			if (id.compareTo(Entrance.customer.getId()) != 0) {
				Request request = new Request();
				request.setType("POW");
				Message msg = new Message();
				msg.setFrom(Entrance.customer.getId());
				msg.setTo(id);
				request.getParameter().put("POW", msg);
				Entrance.client.getClientRunner().write(request);
			}
		}
	};

	// BadRequestCommand=1
	// GetMessageCommand=2
	// PowCommand=3
	// UpdateListCommand=4

	@Override
	public void update(int type, Object object) {

		switch (type) {
		case 1: // BadRequestCommand
			if("shutdown".equals(((Message) object).getContent())){
				JOptionPane.showMessageDialog(this,
						"Server shutdown,Program shutdown", "Error",
						JOptionPane.ERROR_MESSAGE);
				System.exit(1);
			}
			JOptionPane.showMessageDialog(this,
					((Message) object).getContent(), "Error",
					JOptionPane.ERROR_MESSAGE);
			break;
		case 2: // GetMessageCommand
			disArea.setText(disArea.getText() + "\n\r" + (String) object);
			break;
		case 3: // PowCommand
			disArea.setText(disArea.getText() + "\n\r" + (String) object);
			JFrame frmChatroom = this;
			Point location = frmChatroom.getLocation();
			double x = location.getX();
			double y = location.getY();
			for (int i = 0; i < 1000; i++) {
				double offset = Math.pow(-1, i) * 10;
				frmChatroom.setLocation((int) (x + offset), (int) (y + offset));
			}
			frmChatroom.setLocation(location);
			break;
		case 4: // UpdateListCommand
			setVisible(true);
			setTitle("bb chat room vol.1 :Hello " + Entrance.customer.getId());
			final ArrayList<String> userlist = (ArrayList<String>) object;
			SwingUtilities.invokeLater(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					usersModel.clear();
					usersModel.addElement(new String("ALL"));
					for (String userId : userlist) {
						usersModel.addElement(userId);
//						nameList.repaint();
					}
				}
			});
			
			break;
		default:
			break;
		}
	}
	
}
